package com.hxy.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

// 配置类
@Configuration
public class CrosConfig {

    @Bean
    // 优先级：值越低，优先级越高
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public CorsFilter corsFilter(){
        // 跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许的域名
        // corsConfiguration.addAllowedOrigin("http://localhost:8080");
        corsConfiguration.addAllowedOrigin("*");
        // 允许的请求头
        corsConfiguration.addAllowedHeader("*");
        // 请求方式
        corsConfiguration.addAllowedMethod("*");
        // 允许携带凭证
        corsConfiguration.setAllowCredentials(true);

        // 基于请求路径url的跨域源配置
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
